﻿using AuthCenter.Api.Write.Application.Command.Menu;
using AuthCenter.Application;
using AuthCenter.Domain;
using AuthCenter.ErrorCode;
using AutoMapper;
using MediatR;

namespace AuthCenter.Api.Write.Application.Hander.Menu
{
    public class UpdateMenuHander : IRequestHandler<UpdateMenuCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<MenuModel> _menuRepository;
        private readonly IMapper _mapper;
        public UpdateMenuHander(IBaseRepository<MenuModel> menuRepository, IMapper mapper)
        {
            _menuRepository = menuRepository;
            _mapper = mapper;
        }
        /// <summary>
        /// 修改菜单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public Task<ApiResult<int>> Handle(UpdateMenuCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var model = _menuRepository.GetAll().Where(x => x.MenuName == request.MenuName && x.IsDeleted == false).FirstOrDefault();
            if (model != null)
            {
                res.Code = ApiEnums.Error;
                res.Message = "菜单已存在";
            }
            var menu = _mapper.Map<MenuModel>(request);
            menu.UpdateBy = "李四";
            menu.UpdateTime = DateTime.Now;
            menu.CreateBy = "张三";
            menu.CreateTime = DateTime.Now;
            int i = _menuRepository.Update(menu);
            if (i > 0)
            {
                res.Code = ApiEnums.OK;
                res.Message = "修改成功";
                res.Data = i;
            }
            else
            {
                res.Code = ApiEnums.Fail;
                res.Message = "修改失败";
            }
            return Task.FromResult(res);
        }
    }
}
